package com.example.commonlib.base.view;


import com.example.commonlib.base.presenter.RequirePresenter;
import com.example.commonlib.base.presenter.SuperPresenter;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import org.jetbrains.annotations.Nullable;

import java.lang.annotation.Annotation;


/**
 * <p>
 * MVP模型中把Activity作为view层，可通过getPresenter()调用对应的presenter实例
 * <p>
 * Created by linlongxin on 2016/8/3.
 */

public class SuperAbility<P extends SuperPresenter> extends BaseAbility {

    private  final  String TAG = "SuperActivity";
    private P mPresenter;

    @Override
    protected void onStart(@Nullable Intent intent) {
        super.onStart(intent);
        attachPresenter();
        if (mPresenter != null) {
            mPresenter.onCreate(intent);
        }
    }

    /**
     * 在 setContentView 之后回调
     */
    @Override
    public void onInitViews() {
    }

    @Override
    public void onErrorRetry(Component v) {

    }

    public <V extends Component> V $(int id) {
        return (V) findComponentById(id);
    }


    @Override
    public void onActive() {
        super.onActive();
        if (mPresenter != null) {
            mPresenter.onActive();
        }
    }

    private void attachPresenter() {
        if (mPresenter != null) {
            return;
        }
        Annotation[] annotations = getClass().getAnnotations();
        if (annotations.length > 0) {
            for (Annotation annotation : annotations) {
                if (annotation instanceof RequirePresenter) {
                    RequirePresenter presenter = (RequirePresenter) annotation;
                    try {
                        mPresenter = (P) presenter.value().newInstance();
                        mPresenter.attachView(this);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    public P getPresenter() {
        attachPresenter();
        return mPresenter;
    }

    @Override
    protected void onAbilityResult(int requestCode, int resultCode, Intent data) {
        super.onAbilityResult(requestCode, resultCode, data);
        if (mPresenter != null) {
            mPresenter.onAbilityResult(requestCode, resultCode, data);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mPresenter != null) {
            mPresenter.onStop();
        }
    }
}
